<template>
  <panel title="线程">
    <div>
      <div v-if="current" class="content">
        <div class="text-center">
          <p class="font-bold first">活动线程</p>
          <p v-text="current.live" />
        </div>
        <div class="text-center">
          <p class="font-bold second">守护进程</p>
          <p v-text="current.daemon" />
        </div>
        <div class="text-center">
          <p class="font-bold">线程峰值</p>
          <p v-text="current.peak" />
        </div>
      </div>

      <threads-chart v-if="chartData.length > 0" :data="chartData" />
    </div>
  </panel>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import panel from './panel.vue';
import threadsChart from './threads-chart.vue';
import api from "@/http/api";

const current = ref({});
const chartData = ref([]);
const tempData = ref([]);

const fetchMetrics = async() => {
  const responseLive = api.get('/actuator/metrics/jvm.threads.live');
  const responsePeak = api.get('/actuator/metrics/jvm.threads.peak');
  const responseDaemon = api.get('/actuator/metrics/jvm.threads.daemon');

  const data = {
    live: (await responseLive).data.measurements[0].value,
    peak: (await responsePeak).data.measurements[0].value,
    daemon: (await responseDaemon).data.measurements[0].value,
  };

  current.value = data;
  const date = new Date();
  const timestamp = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
  tempData.value.push({...data, timestamp: timestamp});
  if (chartData.value.length <= 2 || tempData.value.length >= 5) {
    chartData.value.push(...tempData.value);
    tempData.value = [];
  }
};

const shutdown = ref(false);
const loopWithDelay = async(taskFn, interval = 1000) => {
  while (!shutdown.value) {
    await taskFn();
    await new Promise(res => setTimeout(res, interval));
  }
}

onMounted(() => {
  loopWithDelay(fetchMetrics);
});

onUnmounted(() => {
  shutdown.value = true;
});
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: row;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  .text-center {
    text-align: center;
    flex-grow: 1;
  }
  .font-bold {
    margin-bottom: 5px;
  }
  .first::before {
    background-color: #FFE6A1;
    content: "";
    width: .75em;
    height: .75em;
    display: inline-block;
    margin-right: .25em;
  }
  .second::before {
    background-color: #65A5D9;
    content: "";
    width: .75em;
    height: .75em;
    display: inline-block;
    margin-right: .25em;
  }
}
</style>
